<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    卡片-->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialog">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1 === 0 ? 'bdtop': '','vctenter']" v-for="(item1,i1) in scope.row.children"
                    :key="item1.id">
              <!-- 一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)" type="success">{{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二、三级权限-->
              <el-col :span="19">
                <!--    二级权限-->
                <el-row :class="['bdtop',i2 === 0 ? '': 'bdtop','vctenter']" v-for="(item2,i2) in item1.children"
                        :key="item2.id">
                  <el-col :span="6">
                    <el-tag closable @close="removeRightById(scope.row,item2.id)">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag closable @close="removeRightById(scope.row,item3.id)" type="warning"
                            v-for="(item3) in item2.children" :key="item3.id">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-search" @click="editRoleDialog(scope.row.id)">编辑
            </el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--  添加角色-->
    <el-dialog title="添加角色" :visible.sync="dialogVisible" width="50%" @close="addDialogClose">
      <el-form :model="addRole" :rules="addRoleRules" ref="addRoleRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRole.roleDesc"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!--  编辑角色-->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form :model="editRole" :rules="editRoleRules" ref="editRoleRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRole.roleDesc"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!--  分配权限-->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClose">
      <!--      树-->
      <el-tree show-checkbox ref="treeRef" :default-checked-keys="defkeys" default-expand-all node-key="id" :data="rightList" :props="treeProps">

      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogClose = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>
export default {
  data() {
    return {
      //默认选中的复选框
      defkeys:[],
      //树形控件属性绑定
      treeProps:{
        label: 'authName',
        children: 'children'
      },
      // 所有角色列表
      roleList: [],
      //添加角色对话框
      dialogVisible: false,
      //编辑角色对话框
      editDialogVisible: false,
      setRightDialogVisible: false,
      //校验规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      //添加角色
      addRole: {
        roleName: '',
        roleDesc: ''
      },
      //更新角色
      editRole: {},
      //所有权限树
      rightList: [],
      //当前需要分配角色的ID
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //分配权限网络请求
    async allotRights(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const {data : res} = await this.$http.post(`roles/${this.roleId}/rights`,{
        rids:idStr
      })
      if( res.meta.status !== 200){
        return this.$message.error(res.meta.msg)
      }
      this.$message.success("分配权限成功！")
      this.getRolesList()
      this.setRightDialogVisible = false
    },
    //分配权限关闭对话框
    setRightDialogClose(){
      this.defkeys = []
    },
    //打开分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取权限树
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.rightList = res.data
      this.getLeafKeys(role,this.defkeys)
      this.setRightDialogVisible = true
    },
    //根据ID删除权限
    async removeRightById(role, rightId) {
      //询问是否删除
      const res = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      //如果取消 返回 cancel
      //如果确定 返回 confirm
      if (res !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: re } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (re.meta.status !== 200) {
        return this.$message.error(re.meta.msg)
      }
      role.children = re.data
    },
    //编辑用户发起网络请求
    editRoles() {
      //校验
      this.$refs.editRoleRef.validate(async (valid) => {
        if (!valid) return
        // console.log(this.editRole)
        const { data: res } = await this.$http.put('roles/' + this.editRole.roleId,
          {
            'roleName': this.editRole.roleName,
            'roleDesc': this.editRole.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        //关闭对话框
        this.editDialogVisible = false
        //刷新列表
        this.getRolesList()
        //提示
        this.$message.success('更新角色成功！')
      })
    },
    //编辑用户对话框打开
    async editRoleDialog(id) {
      //根据ID查询角色显示
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editRole = res.data
      this.editDialogVisible = true
    },
    //删除角色的警告框
    async deleteRole(id) {
      //询问是否删除
      const res = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      //如果取消 返回 cancel
      //如果确定 返回 confirm
      if (res !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      //删除用户的网络请求
      const { data: re } = await this.$http.delete('roles/' + id)
      if (re.meta.status !== 200) {
        return this.$message.error(re.meta.msg)
      }
      this.$message.success('删除角色成功！')
      this.getRolesList()
    },
    //添加角色网络请求
    addRoles() {
      //校验列表
      this.$refs.addRoleRef.validate(async (valid) => {
        if (!valid) return
        //添加角色
        const { data: res } = await this.$http.post('roles', this.addRole)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('添加角色成功！')
        this.dialogVisible = false
        this.getRolesList()
      })
    },
    //打开添加角色对话框
    addDialog() {
      this.dialogVisible = true
    },
    //关闭添加角色对话框
    addDialogClose() {
      this.$refs.addRoleRef.resetFields()
    },
    //编辑角色对话框
    editDialogClose() {
      this.$refs.editRoleRef.resetFields()
    },
    //获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.roleList = res.data
    },
    //获取角色的三级权限ID
    getLeafKeys(node,arr){
      //如果没有children就是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach( item => {
        this.getLeafKeys(item,arr)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vctenter {
  display: flex;
  align-items: center;
}
</style>